import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;
// 统计csdn博客总字数
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-11-18
 * Time: 19:46
 */
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class WordCount {
    // 如果启动不了大抵是驱动问题，更新一下驱动就行了

    private static int totalWordCount = 0;
    private static WebDriver driver;
    @BeforeAll
    static void setUp() {
        ChromeOptions options = new ChromeOptions();
        // 页面加载太慢：禁用JS（关键步骤）
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("profile.managed_default_content_settings.javascript", 2);
        options.setExperimentalOption("prefs", prefs);
//        options.addArguments("-headless"); // 无头模式不能设置
        driver = new ChromeDriver(options);

        // 创建隐式等待，确保页面渲染出来
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        // 全屏
        driver.manage().window().maximize();
    }

    @Order(1)
    @ParameterizedTest
    @ValueSource(ints = {1,2,3})
    void getCount(int pageNum) throws InterruptedException {
        // 打开博客列表页
        driver.get("https://blog.csdn.net/LEE180501/article/list/"+pageNum);
        // 点击只看原创
        WebElement element = driver.findElement(By.cssSelector("#chkOriginal"));
        element.click();

        // 获取文章列表
        List<WebElement> elements = driver.findElements(By.cssSelector("#articleMeList-blog > div.article-list > div"));
        System.out.println("当前页面文章总数："+elements.size());
        for (int i = 0; i < elements.size(); i++) {
            // 获取a标签中的href
            String href = elements.get(i).findElement(By.cssSelector("h4 > a")).getAttribute("href");
            // 跳转到文章页面
            driver.get(href);
            // 计算文字长度
            String text = driver.findElement(By.cssSelector("#mainBox > main > div.blog-content-box > article")).getText();
            int length = text.length();
            // 打印日志
            System.out.println("第 "+pageNum+" 页，"+"第 "+(i+1)+" 篇，文章字数为："+length);
            totalWordCount += length;
            // 返回首页
            driver.navigate().back();
        }
    }

    @Order(2)
    @Test
    void resultCount() {
        System.out.println("-------------------------");
        System.out.println("CSDN 发布原创文章总字数为: "+totalWordCount);
        System.out.println("-------------------------");
    }
}


